package com.itheima.health.service.impl;

import com.itheima.health.common.CodeDataConst;
import com.itheima.health.common.MessageConst;
import com.itheima.health.dto.MobileCodeDTO;
import com.itheima.health.dto.OrderDTO;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.mapper.OrderMapper;
import com.itheima.health.mapper.OrderSettingMapper;
import com.itheima.health.mapper.SetMealMapper;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.MobileValidateCodeService;
import com.itheima.health.service.OrderService;
import com.itheima.health.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MobileValidateCodeService mobileValidateCodeService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Override
    public Order submit(OrderDTO dto) throws ParseException {

        //校验验证码
        String telephone = dto.getTelephone();
        String code = dto.getValidateCode();

        MobileCodeDTO codeDTO = MobileCodeDTO.builder()
                .telephone(telephone)
                .validateCode(code)
                .type(CodeDataConst.ORDER).build();

        if (!mobileValidateCodeService.veriyf(codeDTO)){
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        }

        //注册会员&获取会员信息，后面要用到会员ID
        Member member = memberService.register(dto);
        if (member.getId() == null){
            throw new BusinessRuntimeException(MessageConst.GET_USERNAME_FAIL);
        }

        //校验当天是否预约过
        Date orderDate = new SimpleDateFormat("yyyy-MM-dd").parse(dto.getOrderDate());
        Integer orderCount = orderMapper.selectCountByDateAndMemberId(orderDate, member.getId());
        if (orderCount > 0){
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }

        //计算会员年龄
        Setmeal setmeal = setMealMapper.findById(dto.getSetmealId());
        String ageRange = setmeal.getAge();
        Integer age = memberService.calculateAge(dto.getIdCard());
        //判断用户年龄是否超出套餐年龄范围
        String[] ages = ageRange.split("-");
        if (age > Integer.parseInt(ages[1]) || age < Integer.parseInt(ages[0])){
            throw new BusinessRuntimeException(MessageConst.AGE_OUT_OF_RANGE);
        }

        //预约, 判断预约数
        Order order = Order.builder()
                .orderDate(orderDate)
                .orderType(Order.ORDERTYPE_WEIXIN)
                .memberId(member.getId())
                .orderStatus(Order.ORDERSTATUS_NO)
                .setmealId(dto.getSetmealId()).build();
        //判断是否成功
        Order genOrder = genOrder(order);
        if (genOrder == null){
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }

        return genOrder;

    }

    @Transactional
    Order genOrder(Order order) {
        Date orderDate = order.getOrderDate();
        Integer count = orderSettingMapper.selectAvaildCountByDate(orderDate);

        if (count > 0){
            orderSettingMapper.updateOrderAvaildCount(orderDate);
            orderMapper.insert(order);
            return order;
        }else {
            return null;
        }
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO findById(Integer id) {
        return orderMapper.selectById(id);
    }
}
